import { Table, Space, Card, Form, Button, Select, DatePicker, Input } from 'antd'
import { useStore } from '@/store'
import { useEffect, useState } from 'react'
import { http } from '@/utils'
const { RangePicker } = DatePicker
const Historical = () => {
    const [form] = Form.useForm()
    const [tabsData, setTabsData] = useState([])
    const [historData, setHistorData] = useState([])
    const { loginStore } = useStore()
    const [loading, setLoading] = useState(true)
    const [params, setParams] = useState({
        pageNum: 1,
        pageSize: 20,
        userId: loginStore.userId
    })
    const [factorIdListOpt, setFieldsValue] = useState([])
    const [factorListOpt, setFactorListOpt] = useState([])
    useEffect(() => {
        const getTabs = async () => {
            const res = await http.post('/alarm/deliversign/getAlarmGroupByUserId', { userId: params.userId })
            const list = res.body.length ? res.body.map(item => ({
                label: item.groupAlarmName,
                value: item.id,
                key: item.id
            })) : [{
                label: '--请选择--',
                value: '',
                key: ''
            }]
            console.log('用户预警组', list)
            setTabsData(list)
            await getFactorIdList()
            await getFactor()
            setLoading(false)
        }
        const getFactorIdList = async () => {
            const res = await http.post('/alarm/deliversign/getAllFreq', { userId: params.userId })
            console.log('周期列表-', res.body)
            const list = res.body.map(item => ({
                value: item.id,
                label: item.freqName
            }))
            setFieldsValue(list)
        }
        const getFactor = async () => {
            const res = await http.post('/alarm/deliversign/getAllFactor')
            console.log('因子列表-', res.body)
            const list = res.body.map(item => ({
                value: item.id,
                label: item.factorName
            }))
            setFactorListOpt(list)
        }
        const getList = async () => {
            const res = await http.post('/alarm/deliversign/findTbUserAlarmInfosByUserId', {
                userId: params.userId,
                ...params
            })
            const list = res.body.list.map(item => {
                return {
                    ...item,
                    direction: item.factorName.indexOf('⬇') !== -1 ? 1 : 0,
                    factorName: item.factorName.replace(/⬇|⬆/g, ""),
                }
            })
            console.log('预警组预警消息列表-', list)
            const total = res.body.total
            setHistorData({
                list: list,
                count: total
            })
        }
        if (loading) {
            getTabs()
        } else {
            getList()
        }
    }, [params, loading])
    const columns = [
        {
            title: '品种名称', render: data => {
                return (
                    <Space size="middle">
                        <span>{data.featureName}</span>
                        <span>{data.featureCode}</span>
                    </Space>
                )
            }
        },
        { title: '预警时间', dataIndex: 'datetime', },
        { title: '预警周期', dataIndex: 'freqName', },
        { title: '总分', dataIndex: 'score', },
        {
            title: '预警因子', dataIndex: '', render: data => {
                return (
                    <>
                        <span>{data.factorName}</span>
                        {
                            data.direction ?
                                <svg className="icon" aria-hidden="true" style={{ color: '#00E600' }}>
                                    <use xlinkHref="#icon-paixu"></use>
                                </svg> : <svg className="icon" aria-hidden="true" style={{ color: '#FF3232' }}>
                                    <use xlinkHref="#icon-xiangshang"></use>
                                </svg>
                        }
                    </>
                )
            }
        },
    ]
    const onSeach = (values) => {
        const _params = {
            ...values,
            startTime: values.time ? values.time[0].format('YYYY-MM-DD HH:mm:ss') : '',
            endTime: values.time ? values.time[1].format('YYYY-MM-DD HH:mm:ss') : '',
        }
        setParams({
            ...params,
            ..._params,
            pageNum: 1,

        })
    }
    const pageChange = (page, pageSize) => {
        setParams({
            ...params,
            pageSize: pageSize,
            pageNum: page
        })
    }
    return (
        <>
            <Card title="历史信号">
                <Form
                    form={form}
                    onFinish={onSeach}
                    initialValues={{
                        // time: [moment(date[0], 'YYYY-MM-DD HH:mm'), moment(date[1], 'YYYY-MM-DD HH:mm')]
                    }}
                >
                    <Form.Item style={{ margin: 0 }}>
                        <Form.Item label="预警品种" name="featureName" style={{ display: 'inline-block', width: 240 }}>
                            <Input
                                allowClear
                                placeholder='请输入品种名称'
                                style={{ width: 150 }}
                            />
                        </Form.Item>
                        <Form.Item label="品种代码" name="code" style={{ display: 'inline-block', width: 240 }}>
                            <Input
                                allowClear
                                placeholder='请输入品种代码'
                                style={{ width: 150 }}
                            />
                        </Form.Item>
                        <Form.Item label="所属预警组" name="groupId" style={{ display: 'inline-block', width: 255 }}>
                            <Select
                                style={{ width: 150 }}
                                allowClear
                                placeholder="请选择所属预警组"
                                options={tabsData}
                            />
                        </Form.Item>
                        <Form.Item label="预警周期" name="freqIdList" style={{ display: 'inline-block', width: 240 }}>
                            <Select
                                maxTagCount={1}
                                mode="multiple"
                                style={{ width: 150 }}
                                allowClear
                                placeholder="请选择预警周期"
                                options={factorIdListOpt}
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                            />
                        </Form.Item>
                        <Form.Item label="预警因子" name="factorIdList" style={{ display: 'inline-block', width: 290 }}>
                            <Select
                                maxTagCount={1}
                                mode="multiple"
                                maxTagTextLength={5} // 最长字符6个
                                style={{ width: 200 }}
                                filterOption={(input, option) =>
                                    (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                                }
                                allowClear
                                placeholder="请选择预警因子"
                                options={factorListOpt}
                            />
                        </Form.Item>
                        <Form.Item label="预警时间" name="time" style={{ display: 'inline-block', width: 370, marginRight: 20 }}>
                            <RangePicker
                                format="YYYY-MM-DD HH:mm"
                                showTime={{
                                    format: 'HH:mm',
                                }}
                            />
                        </Form.Item>
                        <Form.Item style={{ display: 'inline-block', width: 100, marginBottom: 10 }}>
                            <Button type="primary" htmlType="submit">
                                查询
                            </Button>
                        </Form.Item>
                    </Form.Item>
                </Form>
                <Table
                    rowKey="id"
                    size='middle'
                    columns={columns}
                    dataSource={historData.list}
                    pagination={
                        {
                            size: 'default',
                            showQuickJumper: true,
                            showSizeChanger: true,
                            pageSize: params.pageSize,
                            onChange: pageChange,
                            showTotal: (total, range) => `共 ${total} 条`,
                            total: historData.count,
                            current: params.pageNum
                        }
                    }
                    bordered
                />
            </Card >
        </>
    )
}

export default Historical